#!/srv/newsblur/venv/newsblur3/bin/python

from vendor.munin.postgres import MuninPostgresPlugin


class MuninPostgresConnectionsPlugin(MuninPostgresPlugin):
    dbname_in_args = False
    title = "Postgres active connections"
    args = "-l 0 --base 1000"
    vlabel = "Active connections"
    info = "Shows active Postgresql connections"

    @property
    def fields(self):
        c = self.cursor()
        c.execute("SHOW max_connections")
        row = c.fetchone()
        return (
            ('connections', dict(
                label = "Active connections",
                info = "Active connections",
                type = "GAUGE",
                warning = int(int(row[0]) * 0.7),
                critical = int(int(row[0]) * 0.8),
            )),
        )

    def execute(self):
        c = self.cursor()
        c.execute("SELECT COUNT(1) FROM pg_stat_activity")
        row = c.fetchone()
        return dict(connections = row[0])

if __name__ == "__main__":
    MuninPostgresConnectionsPlugin().run()
